<template>
  <div>
    <el-card class="no-title-border">
      <div slot="header" style="display: flex; align-items: center">
        <el-button
          type="text"
          icon="el-icon-arrow-left"
          @click="goBack"
        ></el-button>
        <img src="@/assets/images/tx.png" alt="" style="width: 40px; height: 40px; margin-left: 10px"/>
        <div style="font-size: 18px; font-weight: 600; margin-left: 8px">
          {{ robotDetail.bot_name }}
        </div>
        <div style="display: flex;flex-direction: row;position: absolute;right: 4vw;">
          <div :style="{ color: activeTab === 'edit' ? '#7363e9' : '',marginRight:'2vw',cursor: 'pointer' }" @click="handleEdit">编辑</div>
          <div :style="{ color: activeTab === 'publish' ? '#7363e9' : '',cursor: 'pointer' }" @click="handlePublish">发布</div>
        </div>
      </div>
      <!-- 机器人编辑卡片 -->
      <div class="robot-detail-content" v-if="showlj">
        <!-- 机器人设置卡片 -->
        <el-card shadow="hover" class="robot-card1">
          <div style="display: flex; flex-direction: row">
            <img src="@/assets/images/tx.png" alt="" style="width: 50px; height: 50px; margin-left: 10px"/>
            <el-input
              v-model="robotDetail.bot_name"
              maxlength="25"
              show-word-limit
              style="
                  width: 640px;
                  height: 48px;
                  margin-left: 10px;
                  margin-top: 10px;
                "
              class="purple-focus"
            />
          </div>
          <div style="position: relative;width: 100%;max-width: 600px;margin-top: 20px;">
            <span class="title">角色设定</span>
            <el-input
              v-model="robotDetail.prompt_setting"
              type="textarea"
              autosize
              maxlength="2000"
              show-word-limit
              resize="none"
              style="width: 41vw;border-radius: 4px;margin-top: 1.5vh;margin-left: 0.5vw"/>
          </div>
          <div style="position: relative;width: 100%;max-width: 600px;margin-top: 40px;">
            <span class="title">欢迎语</span>
            <el-input
              v-model="robotDetail.welcome_message"
              type="textarea"
              :rows="6"
              maxlength="100"
              show-word-limit
              resize="none"
              style="width: 41vw;border-radius: 4px;margin-top: 1.5vh;margin-left: 0.5vw;"/>
          </div>
          <div class="mxpz_item" style="margin-top: 2vh">
            <span class="title">是否启用缓存：</span>
            <div style="margin-top: 8px">
              <el-radio-group v-model="robotDetail.cache">
                <el-radio :label="false">否</el-radio>
                <el-radio :label="true">是</el-radio>
              </el-radio-group>
            </div>
          </div>
          <div class="submit">
            <span class="title">关联知识库<span class="xinghao">*</span></span>
            <div style="width: 100%; margin-top: 2vh; margin-left: 0.5vw">
              <div
                v-for="(item, idx) in knowledgeList"
                :key="item.value"
                class="zsk"
              >
                <div class="zsk_picture">
                  <i class="el-icon-coin" style="color: #fff; font-size: 16px"></i>
                </div>
                <span style="margin-left: 1vw; font-size: 14px">{{item.kb_name }}</span>
                <i
                  class="el-icon-remove-outline"
                  style="position: absolute;right: 0;color: #999;cursor: pointer;"
                  @click="removeKnowledge(idx)"
                ></i>
              </div>

              <!-- 点击添加 -->
              <div class="zsk" style="justify-content: center; cursor: pointer" @click="openKnowledge">
                <i
                  class="el-icon-circle-plus-outline"
                  style="color: #999"
                ></i>
                <span style="margin-left: 1vw; font-size: 12px; color: #999">
                    点击添加关联知识库
                  </span>
              </div>
            </div>
          </div>
          <el-button type="primary" class="add-btn" style="background-color: #7363e9; margin-left: 38.5vw" @click="updateBot">保存</el-button>
<!--          <span class="title">录入问答</span>-->
<!--          <div-->
<!--            style="-->
<!--                width: 100%;-->
<!--                height: 31vh;-->
<!--                display: flex;-->
<!--                flex-direction: column;-->
<!--                margin-top: 2vh;-->
<!--              "-->
<!--          >-->
<!--            <div style="display: flex; flex-direction: row; margin: 1vh">-->
<!--              <div-->
<!--                :class="{ tab: true, active: qaMode === 'input' }"-->
<!--                @click="qaMode = 'input'"-->
<!--              >-->
<!--                输入问答-->
<!--              </div>-->
<!--              <div-->
<!--                style="margin-left: 2vw"-->
<!--                @click="qaMode = 'batch'"-->
<!--                :class="{ tab: true, active: qaMode === 'batch' }"-->
<!--              >-->
<!--                批量上传-->
<!--              </div>-->
<!--            </div>-->
<!--            <div class="upload_box" v-if="qaMode === 'input'">-->
<!--              <el-input-->
<!--                v-model="question"-->
<!--                maxlength="100"-->
<!--                show-word-limit-->
<!--                style="width: 41vw; margin-left: 10px; margin-top: 10px"-->
<!--              />-->
<!--              <div>-->
<!--                <el-input-->
<!--                  v-model="anwser"-->
<!--                  type="textarea"-->
<!--                  :rows="6"-->
<!--                  maxlength="2000"-->
<!--                  style="-->
<!--                      width: 41vw;-->
<!--                      border-radius: 4px;-->
<!--                      margin-top: 1.5vh;-->
<!--                      margin-left: 0.5vw;-->
<!--                      height: 10vh;-->
<!--                    "-->
<!--                  class="purple-focus"-->
<!--                />-->
<!--                &lt;!&ndash; 当前/最大字数 &ndash;&gt;-->
<!--                <div style="margin-top: 3.5vh; margin-left: 38.5vw">-->
<!--                  {{ anwser.length }}/1000-->
<!--                </div>-->
<!--              </div>-->
<!--              <div-->
<!--                style="display: flex; flex-direction: row; margin-top: 7px"-->
<!--              >-->
<!--                <el-button-->
<!--                  type="primary"-->
<!--                  class="add-btn"-->
<!--                  style="-->
<!--                      background-color: #e7e7e7;-->
<!--                      margin-left: 35vw;-->
<!--                      color: black;-->
<!--                    "-->
<!--                >取消</el-button-->
<!--                >-->
<!--                <el-button-->
<!--                  type="primary"-->
<!--                  class="add-btn"-->
<!--                  style="background-color: #7363e9"-->
<!--                >确认</el-button-->
<!--                >-->
<!--              </div>-->
<!--            </div>-->
<!--            <div class="upload_box" style="" v-else>-->
<!--              &lt;!&ndash; 批量上传区域 &ndash;&gt;-->
<!--              <div class="batch-area">-->
<!--                &lt;!&ndash; 1. 下载模板 &ndash;&gt;-->
<!--                <div class="download-tpl">-->
<!--                  <el-link-->
<!--                    type="primary"-->
<!--                    :underline="false"-->
<!--                    href="/template.xlsx"-->
<!--                    style="color: #7363e9"-->
<!--                    download-->
<!--                  >-->
<!--                    <i class="el-icon-download"></i> 下载模板-->
<!--                  </el-link>-->
<!--                  <span class="tpl-tip"-->
<!--                  >（完成填写后再上传，问题总数不超过 500 条）</span-->
<!--                  >-->
<!--                </div>-->

<!--                &lt;!&ndash; 2. 拖拽 / 点击上传 &ndash;&gt;-->
<!--                <el-upload-->
<!--                  class="upload-panel"-->
<!--                  drag-->
<!--                  multiple-->
<!--                  action="#"-->
<!--                  accept=".xlsx,.xls,.csv"-->
<!--                  :auto-upload="false"-->
<!--                  :limit="1"-->
<!--                  :on-change="handleBatchFile"-->
<!--                  :on-exceed="() => $message.warning('最多上传 1 个文件')"-->
<!--                >-->
<!--                  <i class="el-icon-upload"></i>-->
<!--                  <div class="upload-tip">-->
<!--                    将文件拖到此处，或<em>点击上传</em>-->
<!--                  </div>-->
<!--                </el-upload>-->
<!--              </div>-->
<!--              <div style="display: flex; flex-direction: row">-->
<!--                <el-button-->
<!--                  type="primary"-->
<!--                  class="add-btn"-->
<!--                  style="-->
<!--                      background-color: #e7e7e7;-->
<!--                      margin-left: 35vw;-->
<!--                      color: black;-->
<!--                    "-->
<!--                >取消</el-button-->
<!--                >-->
<!--                <el-button-->
<!--                  type="primary"-->
<!--                  class="add-btn"-->
<!--                  style="background-color: #7363e9"-->
<!--                >确认</el-button-->
<!--                >-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->

          <div class="submit">
            <span class="title">模型配置</span>
            <el-form ref="form" :model="form" :rules="rules" :label-position="'left'" label-width="140px" style="margin-top: 20px">
              <el-form-item label="模型提供方" prop="modelType">
                <el-select v-model="form.modelType" style="width: 100%" @change="changeModelType">
                  <el-option
                    v-for="item in modelTypeOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="自定义模型名称" prop="customType" v-if="form.modelType == '自定义模型配置'">
                <el-input v-model="form.customType"/>
              </el-form-item>
              <el-form-item label="API 密钥" prop="apiKey" v-if="form.modelType != 'ollama'">
                <el-input
                  v-model="form.apiKey"
                  type="password"
                  show-password
                />
              </el-form-item>
              <el-form-item label="API 路径" prop="apiBase">
                <el-input v-model="form.apiBase"/>
              </el-form-item>
              <el-form-item label="模型名称" prop="apiModelName" v-if="form.modelType == 'openAI'">
                <el-select v-model="form.apiModelName" style="width: 100%">
                  <el-option
                    v-for="item in apiModelOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="模型名称" prop="apiModelName" v-else>
                <el-input v-model="form.apiModelName"/>
              </el-form-item>
              <el-form-item label="总Token数量" prop="apiContextLength">
                <el-slider
                  v-model="form.apiContextLength"
                  :min="4096"
                  :max="16384"
                  :step="1024"
                  show-input
                  @change="changeMax"
                />
              </el-form-item>
              <el-form-item label="输出Token数量" prop="maxToken">
                <el-slider
                  v-model="form.maxToken"
                  :min="1"
                  :max="maxValue"
                  show-input
                />
              </el-form-item>
              <el-form-item label="文件分片大小" prop="chunkSize">
                <el-slider
                  v-model="form.chunkSize"
                  :min="1"
                  :max="maxValue"
                  show-input
                />
              </el-form-item>
              <el-form-item label="随机性" prop="temperature">
                <el-slider
                  v-model="form.temperature"
                  :min="0"
                  :max="1"
                  :step="0.01"
                  show-input
                />
              </el-form-item>
              <el-form-item label="累积概率阈值" prop="top_P">
                <el-slider
                  v-model="form.top_P"
                  :min="0"
                  :max="1"
                  :step="0.01"
                  show-input
                />
              </el-form-item>
              <el-form-item label="检索结果数量上限" prop="top_K">
                <el-slider
                  v-model="form.top_K"
                  :min="1"
                  :max="100"
                  show-input
                />
              </el-form-item>
              <el-form-item label="上下文消息数量" prop="context">
                <el-slider
                  v-model="form.context"
                  :min="1"
                  :max="10"
                  show-input
                />
              </el-form-item>
              <el-form-item label="模型能力">
                <el-checkbox v-model="form.capabilities.networkSearch">联网检索</el-checkbox>
                <el-checkbox v-model="form.capabilities.mixedSearch" style="margin-left: 16px">混合检索</el-checkbox>
                <el-checkbox v-model="form.capabilities.onlySearch" style="margin-left: 16px">仅检索模式</el-checkbox>
                <el-checkbox v-model="form.capabilities.rerank" style="margin-left: 16px">检索增强</el-checkbox>
              </el-form-item>
            </el-form>
          </div>

          <el-button
            type="primary"
            style="
                background-color: #7363e9;
                margin-left: 37.5vw;
                width: 4vw;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-top: 2vh"
            @click="submitRobot">确认应用</el-button>
        </el-card>
        <!-- 机器人聊天卡片 -->
        <el-card
          v-loading="chatLoading"
          element-loading-text="完成添加关联知识库后即可预览调试"
          element-loading-spinner="el-icon-lock"
          element-loading-background="rgba(0, 0, 0, 0.4)"
          customClass="chatLoading-content"
          shadow="hover"
          style="
              width: 39vw;
              height: 74vh;
              background-color: white;
              margin-left: 1vw;
              border-radius: 12px;
            "
        >
          <!-- 头部标题 -->
          <div slot="header"
               style="font-size: 16px;font-weight: 600;display: flex;align-items: center;justify-content: center;">
            <img src="@/assets/images/tx.png" alt="" style="width: 30px; height: 30px; margin-right: 10px"/>
            <div>{{ robotDetail.bot_name }}</div>
          </div>

          <!-- 聊天记录区域 -->
          <div
            ref="chatBox"
            style="
                flex: 1 1 auto;
                padding: 12px 16px;
                overflow-y: auto;
                width: 100%;
                height: 58vh;
                scrollbar-width: none;
                -ms-overflow-style: none;
              "
          >
            <div
              v-for="(msg, idx) in chatHistory"
              :key="idx"
              :style="{
                  display: 'flex',
                  marginBottom: '24px',
                  justifyContent:msg.role === 'user' ? 'flex-start' : 'flex-start',
                }"
            >
              <!-- 机器人头像 / 用户头像 -->
              <img
                v-if="msg.role === 'bot'"
                src="@/assets/images/tx.png"
                style="width: 40px;height: 40px;border-radius: 50%;margin-right: 8px;"/>
              <img
                v-else
                src="@/assets/images/yh.png"
                style="width: 40px;height: 40px;border-radius: 50%;margin-right: 8px;"/>
              <div
                v-if="msg.role == 'user'"
                :style="{
                    maxWidth: '100%',
                    padding: '8px 12px',
                    borderRadius: '12px',
                    backgroundColor:'#7363e9',
                    color: '#fff',
                    boxShadow: '0 1px 3px rgba(0,0,0,.1)',
                    wordBreak: 'break-word', // 自动换行
                    overflowWrap: 'break-word',
                    fontSize:'20px'
                  }"
              >
                <div>{{ msg.content }}</div>
              </div>
              <div
                v-if="msg.role == 'bot'"
                :style="{
                    maxWidth: '100%',
                    padding: '8px 12px',
                    borderRadius: '12px',
                    backgroundColor:'#fafafa',
                    color: '#333',
                    boxShadow: '0 1px 3px rgba(0,0,0,.1)',
                    wordBreak: 'break-word', // 自动换行
                    overflowWrap: 'break-word',
                    fontSize:'20px'
                  }"
              >
                <div>{{ msg.status }}</div>
                <div>{{ msg.welcome }}</div>
                <div>{{ msg.answer }}</div>
                <el-collapse v-if="msg.status == '检索完成'"
                             v-model="activeNames"
                             style="margin-top: 10px"
                             @change="handleChange">
                  <div style="margin-top: 10px;font-size: 20px">{{ msg.title }}</div>

                  <el-collapse-item v-for="(item ,index) in msg.content" :title="' 信息来源'+(index+1) +':  ' + item.file_name" :name="item.file_name">
                    <div style="margin-top: 10px;font-size: 18px">{{item.content}}</div>
                    <div style="margin-top: 10px;font-size: 18px">相关性：{{ item.score }}</div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </div>

          <!-- 底部输入框 -->
          <div style="display: flex; align-items: center; padding: 10px 16px 30px 16px">
            <el-input
              v-model="userInput"
              placeholder="请输入问题..."
              @keyup.enter.native="sendMessage"
              size="large"
            ></el-input>
            <el-button
              type="primary"
              icon="el-icon-s-promotion"
              size="large"
              style="margin-left: 8px; background-color: #7363e9"
              :loading="loading"
              @click="sendMessage"
            /></div
          ></el-card>
      </div>
      <!-- 机器人发布卡片 -->
      <div class="robot-detail-content" v-else>
        <el-row :gutter="20" style="width: 100%">
          <el-col :span="8">
            <el-card shadow="hover" style="position: relative;cursor: pointer;height: 150px;border-radius: 12px;margin-top: 10px;">
              <div style="font-size: 16px;font-weight: 100;margin-bottom: 12px;width: 100%;height: 14vh;display: flex;flex-direction: row;">
                <div style="width: 20%; height: 100%">
                  <div
                    style="
                        border-radius: 50%;
                        width: 5vh;
                        height: 5vh;
                        margin-top: 2vh;
                        margin-left: 0.4vw;
                        background-color: #f3f6fd;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                      "
                  >
                    <i class="el-icon-monitor" style="color: #7363e9"></i>
                  </div>
                </div>
                <div
                  style="
                      width: 80%;
                      height: 100%;
                      display: flex;
                      flex-direction: column;
                    "
                >
                  <div style="font-size: 20px;font-weight: 600; color: black; margin-top: 2vh">{{ shareCards.name }}</div>
                  <div style="font-size: 16px; margin-top: 1vh;color: gray">{{ shareCards.show }}</div>
                  <!-- 复制链接 + 预览体验 -->
                  <div
                    style="display: flex;
                    align-items: center;
                    justify-content: space-between;
                    font-size: 14px;
                    width: 10vw;
                    margin-top: 2vh;">
                    <!-- 左侧：包复制链接 -->
                    <el-link
                      type="primary"
                      :underline="false"
                      style="display: flex; align-items: center"
                      @click="copyLink(shareCards.url)"
                    >
                      <i class="el-icon-document-copy" style="margin-right: 4px"></i>
                      复制链接
                    </el-link>

                    <el-link
                      type="primary"
                      :underline="false"
                      style="display: flex; align-items: center"
                      @click="toPreview(shareCards.url)"
                    >
                      <i class="el-icon-view" style="margin-right: 4px"></i>
                      预览体验
                    </el-link>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 复制链接弹窗 -->
      <el-dialog
        title="复制链接"
        :visible.sync="showShareDialog"
        width="30%">
        <div style="margin: 2vh">
          <span class="share-qr" style="font-size: 20px; font-weight: 600">URL 链接：</span>
          <div style="word-wrap: break-word;word-break: break-all;margin-top: 2vh;color: #999;font-size: 14px;">
            {{ shareCards.url }}
          </div>
          <div style="margin-top: 2vh;font-size: 20px; font-weight: 600">二维码：</div>
          <div style="display: flex; flex-direction: row; align-items: center;margin-top: 2vh;">
            <img :src="shareCards.qrCodeUrl" alt="二维码">
            <el-button size="small" @click="saveQr" style="margin-left: 2vw">保存</el-button>
          </div>
          </div>
      </el-dialog>
    </el-card>
    <!-- 关联知识库弹窗 -->
    <el-dialog
      title="选择知识库"
      :visible.sync="dialogVisible"
      width="30%">
      <div style="height: 60vh; overflow-x: hidden; overflow-y: auto">
        <div v-for="(item,index) in knowledgeOptionList" style="height: 100px;width: 100%">
        <div style="background-color: #7363e9;width: 50px;height: 50px;border-radius: 10px;display: inline-block">
          <i class="el-icon-coin" style="color: #fff; font-size: 50px"></i>
        </div>
        <div style="line-height: 50px;font-size: 24px;margin-left: 20px;display: inline-block">{{item.kb_name}}</div>
        <div style="line-height: 50px;margin-right: 20px;display: inline-block;float: right">
          <el-button :disabled="item.status=='已添加'?true:false" style="width: 80px"
                     @click="addKnowledge(item.kb_id)"
          >{{ item.status=='已添加'?'已添加':'添加' }}</el-button>
        </div>
      </div>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { robotDetail,updateRobot,robotAddKb,botChat } from '@/api/robot/index'
import { list } from '@/api/knowledgemanagement/index'
import { getCache } from '@/api/cache/index'
import QRCode from 'qrcode'

export default {
  props: {
    botId: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      robotDetail:[],
      form:{
        modelType:'openAI',
        customType: '',
        apiKey: '',
        apiBase: '',
        apiModelName:'',
        apiContextLength: 4096,
        maxToken: 512,
        chunkSize: 800,
        temperature:0.50,
        top_K: 30,
        top_P: 1.00,
        context: 0,
        capabilities:{
          networkSearch: false,
          mixedSearch: false,
          onlySearch: false,
          rerank: false,
        }
      },
      maxValue:1024,
      rules: {
        modelType: [
          { required: true, message: '模型提供方不能为空', trigger: 'blur' }
        ],
        customType: [
          { required: true, message: '自定义模型名称不能为空', trigger: 'blur' }
        ],
        apiKey: [
          { required: true, message: '模型密钥不能为空', trigger: 'blur' }
        ],
        apiBase: [
          { required: true, message: '模型路径不能为空', trigger: 'blur' }
        ],
        apiModelName: [
          { required: true, message: '模型名称不能为空', trigger: 'blur' }
        ],
        apiContextLength: [
          { required: true, message: '总Token数量不能为空', trigger: 'blur' }
        ],
        maxToken: [
          { required: true, message: '输出Token数量不能为空', trigger: 'blur' }
        ],
        chunkSize: [
          { required: true, message: '文件分片大小不能为空', trigger: 'blur' }
        ],
        temperature: [
          { required: true, message: '随机性不能为空', trigger: 'blur' }
        ],
        top_K: [
          { required: true, message: '累积概率阈值不能为空', trigger: 'blur' }
        ],
        top_P: [
          { required: true, message: '检索结果数量上限不能为空', trigger: 'blur' }
        ],
      },
      modelTypeOptions:['openAI','ollama','自定义模型配置'],
      apiModelOptions:['gpt-3.5-turbo','gpt-3.5-turbo-1106','gpt-3.5-turbo-0125','gpt-3.5-turbo-instruct','gpt-3.5-turbo-16k',
        'gpt-3.5-turbo-16k-0613','gpt-3.5-turbo-16k-0301','gpt-4-0125-preview'],
      chatSettingConfigured:[
        {
          active:false,
          apiBase:"",
          apiContextLength:4096,
          apiKey: "",
          apiModelName:"",
          capabilities: {networkSearch: false, mixedSearch: false, onlySearch: false, rerank: false},
          chunkSize: 800,
          context: 0,
          maxToken: 512,
          modelType: "openAI",
          temperature: 0.5,
          top_K: 30,
          top_P: 1,
        },
        {
          active:false,
          apiBase:"",
          apiContextLength:4096,
          apiKey: "",
          apiModelName:"",
          capabilities: {networkSearch: false, mixedSearch: false, onlySearch: false, rerank: false},
          chunkSize: 800,
          context: 0,
          maxToken: 512,
          modelType: "ollama",
          temperature: 0.5,
          top_K: 30,
          top_P: 1,
        },
        {
          active:false,
          apiBase:"",
          apiContextLength:4096,
          apiKey: "",
          apiModelName:"",
          capabilities: {networkSearch: false, mixedSearch: false, onlySearch: false, rerank: false},
          chunkSize: 800,
          context: 0,
          maxToken: 512,
          modelType: "自定义模型配置",
          temperature: 0.5,
          top_K: 30,
          top_P: 1,
        }
      ],
      dialogVisible: false,
      knowledgeList: [],
      knowledgeOptionList: [],
      chatLoading: false,
      activeNames: [],

      showShareDialog: false,
      shareCards: {
        name: "网页",
        show: "用户在此链接可以直接和您的机器人聊天",
        // url: "http://192.168.34.148:8777/qanything/#/bots/BOT5a8a5a76223f4d1cbc4f66653179c9d1/share",
        url: window.location.protocol + "//" + window.location.hostname + ":" + window.location.port+"/botChat?botId="+this.botId,
        qrCodeUrl: '',
        ewm: require("../img/ewm.png"),
      },

      batchFile: null,
      qaMode: "input",
      anwser: "",

      showlj: true,
      activeTab: "edit",
      chatHistory: [{ role: "bot", welcome: '您好，我是您的专属机器人，请问有什么可以帮您呢？',status:'' }],
      userInput: "",
      loading: false,
      welcome: "",
      question: "请输入问答",
      detailTitle: "",

    };
  },
  created() {

  },
  methods: {
    goBack(){
      this.$emit('back')
    },
    getAllDetails(){
      this.getRobotDetail()
      this.getRobotModel()
    },
    getRobotDetail(){
      robotDetail({bot_id:this.botId}).then(res => {
        this.robotDetail = res.data
        this.knowledgeList = []
        for(let i=0;i<res.data.kb_ids.length;i++){
          var knowSelect = {kb_name:res.data.kb_names[i],kb_id:res.data.kb_ids[i]}
          this.knowledgeList.push(knowSelect)
        }
        if(this.knowledgeList.length>0){
          this.chatLoading = false
        }else{
          this.chatLoading = true
        }
      })
    },
    getRobotModel(){
      if(localStorage.getItem("useChatSetting")){
        this.chatSettingConfigured = JSON.parse(localStorage.getItem("useChatSetting"))
      }
      var newModelTypeOptions = []
      this.chatSettingConfigured.forEach(row => {
        newModelTypeOptions.push(row.modelType)
        if (this.form.modelType === row.modelType) {
          this.form = Object.assign({}, row);
        }
      })
      this.modelTypeOptions = newModelTypeOptions
    },
    updateBot(){
      let param = JSON.parse(this.robotDetail.llm_setting)
      param.bot_id = this.robotDetail.bot_id
      param.bot_name = this.robotDetail.bot_name
      param.prompt_setting = this.robotDetail.prompt_setting
      param.welcome_message = this.robotDetail.welcome_message
      param.cache = this.robotDetail.cache
      updateRobot(param).then(res => {
        this.$message({ message: '保存成功', type: 'success' });
      })
    },
    submitRobot(){
      this.$refs.form.validate(valid => {
        if (valid) {
          if(this.form.modelType == '自定义模型配置'){
            var newConfig = {
              active:false,
              apiBase:this.form.apiBase,
              apiContextLength:this.form.apiContextLength,
              apiKey: this.form.apiKey,
              apiModelName:this.form.apiModelName,
              capabilities: this.form.capabilities,
              chunkSize: this.form.chunkSize,
              context: this.form.context,
              maxToken: this.form.maxToken,
              modelType: this.form.customType,
              temperature: this.form.temperature,
              top_K: this.form.top_K,
              top_P: this.form.top_P,
            }
            this.chatSettingConfigured.push(newConfig)
          }else{
            this.chatSettingConfigured.forEach(row => {
              if (this.form.modelType === row.modelType) {
                row.apiBase = this.form.apiBase
                row.apiContextLength = this.form.apiContextLength
                row.apiKey = this.form.apiKey
                row.apiModelName = this.form.apiModelName
                row.capabilities = this.form.capabilities
                row.chunkSize = this.form.chunkSize
                row.context = this.form.context
                row.maxToken = this.form.maxToken
                row.temperature = this.form.temperature
                row.top_K = this.form.top_K
                row.top_P = this.form.top_P
              }
            })
          }
          localStorage.setItem("useChatSetting", JSON.stringify(this.chatSettingConfigured));
          // this.$message({ message: '应用成功', type: 'success' });
        }
      })
    },
    changeModelType(value){
      if(localStorage.getItem("useChatSetting")){
        this.chatSettingConfigured = JSON.parse(localStorage.getItem("useChatSetting"))
      }
      this.chatSettingConfigured.forEach(row => {
        if (this.form.modelType === row.modelType) {
          this.form = Object.assign({}, row);
        }
      })
      this.$refs.form.resetFields
    },
    changeMax(value){
      this.maxValue = value/1024*256
    },
    handleBatchFile(file) {
      this.batchFile = file.raw;
    },
    handleEdit() {
      this.showlj = true;
      this.activeTab = "edit";
    },
    handlePublish() {
      this.activeTab = "publish";
      this.showlj = false;
      this.activeTab = "publish";
    },
    sendMessage() {
      if (!this.userInput.trim()) return;
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitRobot()
          this.chatHistory.push({ role: "user", content: this.userInput.trim() });
          this.loading = true;
          if(this.robotDetail.cache){
            getCache({bot_id:this.botId,question:this.userInput.trim()}).then(res => {
              this.chatHistory.push({
                role: "bot",
                answer: res.data.data.matched_question,
              });
            }).catch((error) => {
              this.chat()
            }).finally(() => {
              this.loading = false;
              this.userInput = "";
            })
          }else{
            this.chat()
          }
        }else{
          this.$message.info("请先保存模型配置")
        }
      })
    },
    chat(){
      //从本地缓存中读取模型配置
      var useChatSetting = JSON.parse(localStorage.getItem("useChatSetting"))
      var chatSetting = []
      useChatSetting.forEach(row => {
        if (this.form.modelType === row.modelType) {
          chatSetting = Object.assign({}, row);
        }
      })
      let param = {
        api_base: chatSetting.apiBase,
        api_context_length: chatSetting.apiContextLength,
        api_key: chatSetting.apiKey,
        bot_id: this.botId,
        chunk_size: chatSetting.chunkSize,
        history: [],
        hybrid_search: chatSetting.capabilities.mixedSearch,
        max_token: chatSetting.maxToken,
        model: chatSetting.apiModelName,
        networking: chatSetting.capabilities.networkSearch,
        only_need_search_results: chatSetting.capabilities.onlySearch,
        product_source: "saas",
        question: this.userInput.trim(),
        rerank: chatSetting.capabilities.rerank,
        streaming: false,
        temperature: chatSetting.temperature,
        top_k: chatSetting.top_K,
        top_p: chatSetting.top_P,
      }

      botChat(param).then(res => {
        var data = JSON.parse(res.substring(5)).source_documents
        this.chatHistory.push({
          role: "bot",
          status: '检索完成',
          title: "找到了"+data.length +'个信息来源：',
          content: data,
        });
        this.$nextTick(() => {
          const box = this.$refs.chatBox;
          box.scrollTop = box.scrollHeight;
        });
      }).finally(() => {
        this.loading = false;
        this.userInput = "";
      })
    },
    openKnowledge() {
      this.dialogVisible = true
      list().then(res => {
        this.knowledgeOptionList = res.data;
        this.knowledgeOptionList.forEach(row => {
          this.knowledgeList.forEach(row2 => {
            if(row.kb_id == row2.kb_id){
              row.status = '已添加'
            }
          })
        })
      })
    },
    addKnowledge(id){
      var kbIds = []
      this.knowledgeList.forEach(row => {
        kbIds.push(row.kb_id)
      })
      kbIds.push(id)
      robotAddKb({bot_id: this.botId,kb_ids:kbIds}).then(res => {
        this.getRobotDetail()
        this.knowledgeOptionList.forEach(row => {
          if(row.kb_id == id){
            row.status = '已添加'
          }
        })
      })
    },
    removeKnowledge(idx) {
      this.knowledgeList.splice(idx, 1);
      var kbIds = []
      this.knowledgeList.forEach(row => {
        kbIds.push(row.kb_id)
      })
      robotAddKb({bot_id: this.botId,kb_ids:kbIds}).then(res => {
        this.getRobotDetail()
      })
    },
    handleChange(val) {
    },
    copyLink(url){
      this.showShareDialog = true
      this.createQrCode(url)
    },
    async createQrCode(url){
      this.shareCards.qrCodeUrl = await QRCode.toDataURL(url, {
        width: 200,
        errorCorrectionLevel: 'H'
      });
    },
    toPreview(url){
      window.open(url, '_blank');
    },
    saveQr(){
      var downUrl = this.shareCards.url
      QRCode.toDataURL(downUrl,{
        width: 200,
        errorCorrectionLevel: 'H'
      }, (err, url) => {
        const link = document.createElement('a');
        link.href = url;
        link.download = 'qrcode.png';
        link.click();
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.no-title-border {
  border-radius: 12px;
  min-height: 85vh;
  background-color: #f3f6fd;
  ::v-deep.el-card__header {
    border-bottom: 0;
  }
}

.robot-detail-content {
  height: 74vh;
  width: 83vw;
  display: flex;
  flex-direction: row;
}

.robot-card1{
  width: 46vw;
  height: 74vh;
  background-color: white;
  overflow-y: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

::v-deep .el-input__inner:focus {
  border-color: blueviolet;
}
.el-input--medium .el-input__inner {
  border-radius: 2px;
}

::v-deep .el-textarea__inner:focus {
  border-color: blueviolet;
  max-height: 30vh;
}
.el-textarea__inner:hover {
  border-radius: 2px;
}
::v-deep.el-textarea__inner {
  max-height: 30vh;
}
::v-deep .purple-focus .el-textarea__inner {
  max-height: 13vh;
  min-height: 15vh;
}

.title {
  margin: 10px;
  font-weight: 550;
  font-size: 14px;
}
.zsk {
  width: 100%;
  height: 6vh;
  background-color: #f9f9fc;
  border-radius: 4px;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 1vh;

  .zsk_picture {
    width: 4vh;
    height: 4vh;
    background-color: #7363e9;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    margin-left: 1.5vw;
  }
}

.submit {
  position: relative;
  width: 100%;
  margin-top: 40px;
}
.mxpz_item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
.mxpz_title {
  width: 10vw;
  font-size: 12px;
  color: #333;
  margin-left: 0.5vw;
  display: flex;
  align-items: center;
}

::v-deep.el-slider__bar {
  background-color: #7363e9;
}
::v-deep.el-slider__button {
  border: solid 2px #7363e9;
  width: 12px;
  height: 12px;
}
::v-deep.el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #7363e9;
  border-color: #7363e9;
}

.xinghao {
  color: #f56c6c;
  font-size: 16px;
  font-weight: 500;
}
.mxpz_xh {
  margin-top: 5px;
}
.mxpz_value {
  margin-left: 12px;
  font-size: 14px;
  color: #666;
  width: 6vw;
  height: 3vh;
  /* border: solid 1px #999; */
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.upload_box {
  width: 100%;
  height: 82%;
}

.tab {
  cursor: pointer;
  color: #666;
}
.tab.active {
  color: #7363e9;
  font-weight: 600;
}
.add-btn {
  width: 3vw;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 2vh;
}

.batch-area {
  width: 100%;
  height: 23vh;
  background-color: #f3f6fd;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .download-tpl {
    display: flex;
    flex-direction: row;
  }
}

::v-deep {
  .el-loading-spinner i{
    font-size: 4.8vh;
    color: #fff;
    margin-bottom: 20px;
  }

  .el-loading-spinner .el-loading-text {
    font-size: 2.8vh;
    color: #fff;
  }
}
</style>
